"""
基础服务类
"""
from extension import db


class BaseService:
    """所有服务的基类"""
    
    def __init__(self, model):
        self.model = model
    
    def get_by_id(self, id):
        """根据ID获取记录"""
        return self.model.query.get(id)
    
    def get_all(self, page=1, per_page=10, **filters):
        """获取所有记录（分页）"""
        query = self.model.query
        
        # 应用过滤条件
        for key, value in filters.items():
            if value is not None and hasattr(self.model, key):
                query = query.filter(getattr(self.model, key) == value)
        
        return query.paginate(page=page, per_page=per_page, error_out=False)
    
    def create(self, **data):
        """创建记录"""
        instance = self.model(**data)
        db.session.add(instance)
        db.session.commit()
        return instance
    
    def update(self, id, **data):
        """更新记录"""
        instance = self.get_by_id(id)
        if not instance:
            return None
        
        for key, value in data.items():
            if hasattr(instance, key) and value is not None:
                setattr(instance, key, value)
        
        db.session.commit()
        return instance
    
    def delete(self, id):
        """删除记录"""
        instance = self.get_by_id(id)
        if not instance:
            return False
        
        db.session.delete(instance)
        db.session.commit()
        return True
